package com.coldwindblows.blog.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.coldwindblows.blog.dao.UserMapper;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.UserDo;
import com.coldwindblows.blog.service.IUserService;
import com.coldwindblows.blog.utils.TaleUtils;

/**
 * Created by ColdWindBlows on 2018/07/04
 *
 */
@Service
public class IUserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userDao;
	
	@Transactional
	@Override
	public Integer insertUser(UserDo user) {
		if(StringUtils.isNotBlank(user.getUsername()) && StringUtils.isNotBlank(user.getEmail())) {
			// 密码+盐
			String salt = TaleUtils.getSalt();
			String encodePwd = TaleUtils.getHashPassword(salt, user.getPassword());
			user.setSalt(salt);
			user.setPassword(encodePwd);
			userDao.insert(user);
		}
		return user.getUid();
	}

	@Override
	public UserDo queryUserById(Integer uid) {
		if(uid != null) {
			return userDao.selectByPrimaryKey(uid);
		}
		return null;
	}

	@Override
	public UserDo login(String username, String password) {
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			throw new TipException("用户名和密码不能为空");
		}
		UserDo user = userDao.selectByUsername(username);
		if(user == null) {
			throw new TipException("不存在该用户");
		}
		String inputPwd = TaleUtils.getHashPassword(user.getSalt(), password);
		if(TaleUtils.pwdCompare(inputPwd, user.getPassword())) {
			return user;
		}
		throw new TipException("用户名或密码错误");
	}
	
	@Override
	public UserDo regiest(String username, String password, String nickname, String email) {
		UserDo user = userDao.selectByUsername(username);
		if(user != null) {
			throw new TipException("该用户已被使用，请直接登录");
		}
		String salt = TaleUtils.getSalt();
		String pwd = TaleUtils.getHashPassword(salt, password);
		user = new UserDo();
		user.setUsername(username);
		user.setPassword(pwd);
		user.setSalt(salt);
		user.setScreenName(nickname);
		user.setEmail(email);
		user.setCreated(new Date());
		userDao.insert(user);
		return user;
	}

	@Transactional
	@Override
	public boolean updateByUid(UserDo user) {
		if(null == user || null == user.getUid()) {
			throw new TipException("user is null");
		}
		int result = userDao.updateByPrimaryKey(user);
		if(result != 1) {
			throw new TipException("update user by uid and return is not one");
		}
		return true;
	}

}
